package servlets;

// Servlet Test.java  de test de la configuration
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/servlet/Login")
public class LoginServlet extends HttpServlet {
	/**
	 * SID
	 */
	private static final long serialVersionUID = 1L;

	public void service(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		PrintWriter out = res.getWriter();
		res.setContentType("text/html");
		Connection con = null;

		try {
			Class.forName("org.postgresql.Driver"); // mettre le driver dans le

			// connexion a la base
			String urlBDD = "jdbc:postgresql://sqlserv/da2i";
			String nomBDD = "ricqh";
			String mdpBDD = "moi";

			con = DriverManager.getConnection(urlBDD, nomBDD, mdpBDD);
			// execution de la requete
			String login = req.getParameter("login");
			String mdp = req.getParameter("mdp");

			PreparedStatement prep = con
					.prepareStatement("SELECT * FROM Utilisateur WHERE login = ? AND mdp = ?");
			// String query =

			prep.setString(1, login);
			prep.setString(2, mdp);

			ResultSet rs = prep.executeQuery();

			if (rs.next()) {
				HttpSession session = req.getSession(true);
				session.setAttribute("login", login);
				session.setAttribute("role", rs.getString("role"));
				out.println("1");
			} else {
				out.println("2");
			}
		} catch (Exception e) {
			throw new ServletException("ErrorConTraitement " + e.getMessage(),
					e);
		}

		finally {
			try {
				con.close();
			} catch (Exception d) {
				throw new ServletException("ErrorFinally " + d.getMessage(), d);
			}
		}

	}
}